
import fs from 'fs'
import path from 'path'
import Parser from './parser'
import Benchmark from 'benchmark'

function readFile (file) {
  return fs.readFileSync(file, 'utf8')
}

function readdir (dir) {
  return fs.readdirSync(dir)
}

main()

function main () {
  let
    fixture = [],
    totalSize = 0,
    totalTime = 0,
    totalRme  = 0,
    argv = process.argv.slice(2)

  if (!argv.length)
    argv = ['../modules/any/*.zxx']

  argv.forEach(s => {


    s = path.resolve(s)
    let
      dir = path.dirname(s),
      a = path.basename(s) === '*.zxx'
      && readdir(dir).filter(s =>
        path.extname(s) === '.zxx'
      ).map(s => path.join(dir, s))
      || path.extname(s) === '.zxx'
      && [s]
      || []

    a.forEach(s => {
      if (
        fs.existsSync(s)
      && fs.statSync(s).isFile()
      ) {
        let src = readFile(s)
        if (src) {
          totalSize += src.length
          fixture.push([src, s])
        }
      }
    })
  })

  fixture.reduce(function (suite, [src, path]) {
    return suite.add(path, function () {
      new Parser().parse(src, path)
    }, {
      onComplete: function (event) {
        if (typeof gc === 'function') {
          console.log('...')
          gc()
        }
        totalTime += this.stats.mean
        totalRme += this.stats.mean * this.stats.rme * this.stats.rme
      }
    })
  }, new Benchmark.Suite()).on('complete', function () {
    console.log(fixture.length + ' files ' +
      (totalSize / 1024).toFixed(2) + ' KiB ' +
      (1000 * totalTime).toFixed(2) + ' ms ' +
      '\xb1' + Math.sqrt(totalRme / totalTime).toFixed(2) + '%'
    )
  }).run()
}
